$(() => {
    load();
});
const reLoad = () => {
    $('#exampleTable').bootstrapTable('refresh')
}

const divShake=(layero)=>{
    if(null!=layero&&''!=layero){
        $(layero).addClass('animate__animated animate__fadeIn')
        $(layero).on('animationend', function() {
            $(this).removeClass('animate__animated animate__fadeIn');
        });
    }
}

$('#searchState').change(function () {
    reLoad()
})


const setGrade = async (isadd, title, item,url) => {
    const oneAndTwoData = await getOneAndTwo()
    let myOption = '', title1 = '', title2 = '', formitem = '', oldSelectExist = false,
        mySelect = isadd ? `<select name="num2" id="myselect1" lay-search="" lay-verify="required" lay-filter="aihao">` :
            ` <select name="num2" id="myselect1" lay-search="" value="${item.num2}" lay-verify="required" lay-filter="aihao" disabled>`
    for (let i = 0; i < oneAndTwoData.length; i++) {
        if (oneAndTwoData[i].num2 != '-') {
            if (isadd) {
                myOption += ` <option value="${oneAndTwoData[i].num2}">${oneAndTwoData[i].num2}</option>`
            } else {
                if (oneAndTwoData[i].num2 == item.num2 &&null!=item.num2 ) {
                    myOption += ` <option value="${oneAndTwoData[i].num2}" selected>${oneAndTwoData[i].num2}</option>`
                    oldSelectExist = true
                } else {
                    myOption += ` <option value="${oneAndTwoData[i].num2}">${oneAndTwoData[i].num2}</option>`
                }
            }
        }
    }
    if (!oldSelectExist && null != item && Object.keys(item).length > 0) {
        myOption += ` <option value="${item.num2}" selected>${item.num2}</option>`
    }
    title2 =   '婴幼儿早期学习裁判录分'


    formitem += `

                      <div class="layui-form-item">
        <label class="layui-form-label" style="width:auto;border: 0;">${title2}</label>
  </div>
                      <div class="layui-form-item" style="display: flex; gap: 10px;">
  <div style="width: 33%;">
     <label class="layui-form-label" style="width:120px;border: 0;text-align: left;">裁判1</label>
        <input name="moduleTwoMarkOne" placeholder="" autocomplete="off"
        onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')"
        value="${isadd ? '' : item.score1s}"
        class="layui-input" lay-verify="maxValue1||required" min="0" step="1" lay-affix="number">
  </div>
  <div style="width: 33%;">
     <label class="layui-form-label" style="width:120px;border: 0;text-align: left;">裁判2</label>
        <input name="moduleTwoMarkTwo" placeholder="" autocomplete="off"
        onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')"
        value="${isadd ? '' : item.score2s}"
        class="layui-input" lay-verify="maxValue1||required" min="0" step="1" lay-affix="number">
  </div>
  <div style="width: 33%;">
     <label class="layui-form-label" style="width:120px;border: 0;text-align: left;">裁判3</label>
        <input name="moduleTwoMarkThree" placeholder="" autocomplete="off"
        onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')"
        value="${isadd ? '' : item.score3s}"
        class="layui-input" lay-verify="maxValue1||required" min="0" step="1" lay-affix="number">
  </div>
  </div>
                      <div class="layui-form-item" style="display: flex; gap: 10px;">
  <div style="width: 33%;">
     <label class="layui-form-label" style="width:120px;border: 0;text-align: left;">裁判4</label>
        <input name="moduleTwoMarkFour" placeholder="" autocomplete="off"
        onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')"
        value="${isadd ||null==item.score4s? '' : item.score4s}"
        class="layui-input" lay-verify="maxValue1||score4Value1" min="0" step="1" lay-affix="number">
  </div>
  <div style="width: 33%;">
     <label class="layui-form-label" style="width:120px;border: 0;text-align: left;">裁判5</label>
        <input name="moduleTwoMarkFive" placeholder="" autocomplete="off"
        onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')"
        value="${isadd ||null==item.score5s? '' : item.score5s}"
        class="layui-input" lay-verify="maxValue1||lastrequired1" min="0" step="1" lay-affix="number">
  </div>
  </div>
 <div class="layui-form-item">
        <label class="layui-form-label" style="width:auto;border: 0;">备注</label>
         <div class="layui-input-block">
      <input type="text" name="remarkB" placeholder="请输入" autocomplete="off" value="${isadd ? '' : item.remarkB}" class="layui-input">
    </div>
  </div>
                        `
    //分数
    let toIndex = layer.open({
        type: 1,
         area: ['500px', '70%'] ,
        title: title,
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">
       <div class="layui-form-item">
    <label class="layui-form-label" style="width:21%;border: 0; text-align: left;">赛场信息</label>
               <input type="text" style="width: calc(100% - 143px);" disabled autocomplete="off" class="layui-input race-course" value="${$('#searchState').val()}">
  
  </div>
    <div class="layui-form-item">
    <label class="layui-form-label" style="width:21%;border: 0; text-align: left;">二次加密号</label>
    <div class="layui-input-inline" style="width: calc(100% - 143px);">
       ${mySelect}
        <option value="">请选择二次加密序号</option>
       ${myOption}
      </select>
    </div>
  </div>
 ${formitem}
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="layui-btn" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form>
                `,
        success: (layero, index) => {
            layui.use(['form'], () => {
                setTimeout(()=>{
                    selectInput('myselect1',layero)
                },50)
                var form = layui.form;
                let score4Values='',score4Values1=''
                form.verify({
                    maxValue: (value, item) => {
                        if (''!=value&&parseInt(value) >40) {
                            return '请勿超过40分';
                        }
                    },
                    maxValue1: (value, item) => {
                        if (''!=value&&parseInt(value) >40) {
                            return '请勿超过40分';
                        }
                    },
                    score4Value:(value,item)=>{
                     score4Values=value
                    },
                     lastrequired:(value,item)=>{
                      if (value !== '') {
                        if(parseInt(value) > 40){
                            return '请勿超过40分';
                        }
                        console.log(score4Values)
                        if(score4Values==''||null==score4Values){
                            return '请先进行裁判4录分'
                        }
                    }
                }, score4Value1:(value,item)=>{
                        score4Values1=value
                    },
                    lastrequired1:(value,item)=>{
                        if (value !== '') {
                            if(parseInt(value) > 40){
                                return '请勿超过40分';
                            }
                            if(score4Values1==''||null==score4Values1){
                                return '请先进行裁判4录分'
                            }
                        }
                    }
                });
                form.render('select');
                setTimeout(()=>{
                    selectInput('myselect1',layero)
                },50)
                form.render();
                form.on('submit(layedit-code-yes)', function (data) {
                    const mydata = data.field
                    //第一次确认
                    if ('提交' == $(data.elem).text()) {
                        $(data.elem).text('确认数据')
                        divShake(layero)
                        for (let i = 0; i < data.form.length - 1; i++) {
                            let element = data.form[i]
                            $(element).prop('disabled', true)
                        }
                    } else {
                        console.log('提交数据', data, mydata)
                        let otherData = {}
                        if (isadd) {
                            otherData = {
                                status: 0
                            }
                        } else {
                            otherData = {
                                status: 0,
                                id: item.id
                            }
                        }
                        let tows = {
                            moduleOneMarkOne:item.score1,
                            moduleOneMarkTwo:item.score2,
                            moduleOneMarkThree:item.score3,
                            moduleOneMarkFour:item.score4,
                            moduleOneMarkFive:item.score5,
                            remark:item.remarkA
                        }
                        $.ajax({
                            type: 'post',
                            data: JSON.stringify({
                                ...tows,
                                ...mydata,
                                field:$('#searchState').val(),
                                ...otherData,
                                bs:'B1',
                                type:2

                            }),
                            contentType: 'application/json',
                            url: url,
                            success: function (r) {
                                if (r.code == 0) {
                                    reLoad()
                                    //逻辑处理
                                    for (let i = 0; i < data.form.length - 1; i++) {
                                        let element = data.form[i]
                                        $(element).prop('disabled', false)
                                        const OP = $(element).find("option")
                                        if (OP.length > 0) {
                                            //下一步
                                            let mj = '';
                                            for (let j = 0; j < OP.length; j++) {
                                                const OPItem = OP[j]
                                                if ($(element).val() == $(OPItem).val()) {
                                                    mj = j + 1;
                                                }
                                            }
                                            //设置禁止选择
                                            $(element)[0].options[mj - 1].disabled = true;
                                            for (let j = 1; j < OP.length; j++) {
                                                const OPItem = OP[j]
                                                if (''==OPItem.disabled||!OPItem.disabled) {
                                                    mj = j;
                                                    break;
                                                }
                                            }
                                            isEnd = mj == OP.length;
                                            $(element).prop('value', $(OP[mj]).val())
                                            $('.race-course').val($('#searchState').val())
                                            form.render('select');
                                            setTimeout(()=>{
                                                selectInput('myselect1',layero)
                                            },50)
                                            //如何滚动顶部
                                            layero.find('.layui-layer-content').animate({ scrollTop: 0 }, 'fast');
                                        } else {
                                            $(element).val("")
                                        }
                                    }
                                    $(data.elem).text('提交')
                                    divShake(layero)
                                    form.render();
                                    layer.msg(mydata.num2+'录入分数成功');
                                    if (isEnd || !isadd) {
                                        layer.close(index);
                                    }
                                } else {
                                    layer.msg(mydata.num2+'录入分数失败');
                                }
                            }
                        });


                    }

                });
            })


        }
    });
    layer.full(toIndex);
}
const getOneAndTwo = () => {
    return new Promise((resolve, reject) => {
        let pData = {
            current: 1,
            size: 10000,
            field:$('#searchState').val(),
            type:2
        }
        $.ajax({
            type: 'post',
            data:  JSON.stringify(pData)  ,
            contentType: 'application/json',
            url: '/getNum2Init',
            success: function (r) {
                if (r.code == 0) {
                    resolve(  r.data.records )
                } else {
                    layer.msg(r.msg);
                    reject(r)
                }
            }
        });
    })
}
const EntryScore = async (item = null) => {
    console.log('=====>>录入分数>', item)
    setGrade(true, '婴幼儿早期学习赛场录入分数', '','/recordPoints/recordPoints')

}



const derive = () => {
    console.log('=====>>导出>' )
    //apiDerive
    layer.confirm(`是否导出婴幼儿早期学习赛场二次加密与分数信息？`, {
        btn1: function (index) {
            window.location.href =`/recordPoints/downloadMark?field=${$('#searchState').val()}&bs=B1&type=2`;
            layer.close(index)
        }
    });
}

const edit = (mydata) => {
    console.log('=====>>修改>', mydata)
    setGrade(false,'修改', mydata,'/recordPoints/recordPoints2')

}

const columns =  [
    {
        field: 'num2',
        title: '第二次加密号',
        width: '105px'
    },
    {
        field: 'score1s',
        title: '裁判一',
        width: '180px',
        formatter: function (value, row, index) {
            return parseInt(value) === -1 ? 0 : value
        }
    },
    {
        field: 'score2s',
        title: '裁判二',
        width: '180px',
        formatter: function (value, row, index) {
            return parseInt(value) === -1 ? 0 : value
        }
    },
    {
        field: 'score3s',
        title: '裁判三',
        width: '180px',
        formatter: function (value, row, index) {
            return parseInt(value) === -1 ? 0 : value
        }
    },
    {
        field: 'score4s',
        title: '裁判四',
        width: '180px',
        formatter: function (value, row, index) {
            return parseInt(value) === -1 ? 0 : value
        }
    },
    {
        field: 'score5s',
        title: '裁判五',
        width: '180px',
        formatter: function (value, row, index) {
            return parseInt(value) === -1 ? 0 : value
        }
    },
    {
        field: 'remarkB',
        title: '备注',
        width: '105px',

    },
    {
        title: '操作',
        field: 'id',
        align: 'center',
        // width:'50px',
        formatter: function (value, row, index) {
            return `
                                    <a style="color: #18a689" class=" " href="#" mce_href="#" title="修改" onclick="edit(${JSON.stringify(row).replace(/\"/g, "'")})">修改</a>
                                    `;
        },
        width: '230px'
    }]
columns.forEach(item => {
    item.align = 'center'
    item.valign='middle'
})

function load() {
    $('#exampleTable')
        .bootstrapTable(
            {
                method: 'get', // 服务器数据的请求方式 get or post
                url: '/recordPoints/getScoreInfoPage', // 服务器数据的加载地址
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                //search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType: "",
                queryParams: function (params) {
                    console.log('params', params)
                    return {
                        current: params.pageNumber,
                        size: params.pageSize,
                        field:$('#searchState').val(),
                        bs:'B1',
                        type:2
                    };
                },
                responseHandler: function (res) {
                    if (res.code !== '0') {
                        layer.msg(res.msg);
                        return false
                    }
                    return {
                        "rows": res.data.records,
                        ...res.data
                    };
                },
                columns
            });
}